package GUI;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import model.Contact;
import control.PersonCtrl;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.Color;

public class contacts extends JFrame {

	private final TableRowSorter<TableModel> sorter;
	private JPanel contentPane;
	private JTextField tfCCcpr;
	private JTextField tfCCname;
	private JTextField tfCCaddress;
	private JTextField tfCCzipCode;
	private JTextField tfCCcity;
	private JTextField tfCCphone;
	private JTextField tfCCgsm;
	private JTextField tfCCemail;
	private JTable contactsTable;
    private PersonCtrl personCtrl = new PersonCtrl();
    private static contactTable contactsT = new contactTable();
    private JTextField tfSearch;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					contacts frame = new contacts();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public contacts() {
		setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Andrada\\Desktop\\images.jpg"));
		setTitle("CONTACTS");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 1050, 600);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(255, 255, 153));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 81, 692, 470);
		contentPane.add(scrollPane);
		
		contactsTable = new JTable();
		contactsTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]{},
                new String []
                {
                            "Name", "Address", "Zipcode", "City", "Phone", "GSM", "E-mail", "CPR"
                }));
		sorter = new TableRowSorter<TableModel>(contactsT);
		contactsTable.setRowSorter(sorter);
		scrollPane.setViewportView(contactsTable);
		
		JLabel lblListOfContacts = new JLabel("LIST OF CONTACTS");
		lblListOfContacts.setHorizontalAlignment(SwingConstants.CENTER);
		lblListOfContacts.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblListOfContacts.setBounds(10, 7, 692, 31);
		contentPane.add(lblListOfContacts);
		
		JPanel contactsPanel = new JPanel();
		contactsPanel.setBackground(new Color(255, 255, 153));
		contactsPanel.setLayout(null);
		contactsPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Contact Control", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		contactsPanel.setBounds(712, 50, 312, 501);
		contentPane.add(contactsPanel);
		
		JLabel lblCCcpr = new JLabel("CPR :");
		lblCCcpr.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCcpr.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCcpr.setBounds(6, 16, 114, 31);
		contactsPanel.add(lblCCcpr);
		
		tfCCcpr = new JTextField();
		tfCCcpr.setColumns(10);
		tfCCcpr.setBounds(130, 20, 170, 25);
		contactsPanel.add(tfCCcpr);
		
		JLabel lblCCname = new JLabel("Name :");
		lblCCname.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCname.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCname.setBounds(6, 58, 114, 31);
		contactsPanel.add(lblCCname);
		
		JLabel lblCCaddress = new JLabel("Address :");
		lblCCaddress.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCaddress.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCaddress.setBounds(6, 100, 114, 31);
		contactsPanel.add(lblCCaddress);
		
		tfCCname = new JTextField();
		tfCCname.setColumns(10);
		tfCCname.setBounds(130, 62, 170, 25);
		contactsPanel.add(tfCCname);
		
		tfCCaddress = new JTextField();
		tfCCaddress.setColumns(10);
		tfCCaddress.setBounds(130, 104, 170, 25);
		contactsPanel.add(tfCCaddress);
		
		JLabel lblCCzipCode = new JLabel("Zip Code :");
		lblCCzipCode.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCzipCode.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCzipCode.setBounds(6, 142, 114, 31);
		contactsPanel.add(lblCCzipCode);
		
		JLabel lblCCcity = new JLabel("City :");
		lblCCcity.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCcity.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCcity.setBounds(6, 184, 114, 31);
		contactsPanel.add(lblCCcity);
		
		JLabel lblCCphone = new JLabel("Phone :");
		lblCCphone.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCphone.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCphone.setBounds(6, 226, 114, 31);
		contactsPanel.add(lblCCphone);
		
		JLabel lblCCgsm = new JLabel("GSM :");
		lblCCgsm.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCgsm.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCgsm.setBounds(6, 268, 114, 31);
		contactsPanel.add(lblCCgsm);
		
		JLabel lblCCemail = new JLabel("Email :");
		lblCCemail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCCemail.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblCCemail.setBounds(6, 310, 114, 31);
		contactsPanel.add(lblCCemail);
		
		tfCCzipCode = new JTextField();
		tfCCzipCode.setColumns(10);
		tfCCzipCode.setBounds(130, 146, 170, 25);
		contactsPanel.add(tfCCzipCode);
		
		tfCCcity = new JTextField();
		tfCCcity.setColumns(10);
		tfCCcity.setBounds(130, 188, 170, 25);
		contactsPanel.add(tfCCcity);
		
		tfCCphone = new JTextField();
		tfCCphone.setColumns(10);
		tfCCphone.setBounds(130, 230, 170, 25);
		contactsPanel.add(tfCCphone);
		
		tfCCgsm = new JTextField();
		tfCCgsm.setColumns(10);
		tfCCgsm.setBounds(130, 272, 170, 25);
		contactsPanel.add(tfCCgsm);
		
		tfCCemail = new JTextField();
		tfCCemail.setColumns(10);
		tfCCemail.setBounds(130, 314, 170, 25);
		contactsPanel.add(tfCCemail);
		
		contactsTable.addMouseListener(new MouseAdapter() {
      	  public void mouseClicked(MouseEvent e) {
      	    if (e.getClickCount() == 2) {
      	      JTable target = (JTable)e.getSource();
      	      int row = target.getSelectedRow();
      	      setContactFields((String)contactsTable.getModel().getValueAt(row, 7));
      	    }
      	  }
      	});
		
		JButton btnCCadd = new JButton("Add");
		btnCCadd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
                if(ifContactExists())
        		{
        			JOptionPane.showMessageDialog(null,"Contact with this CPR already exists.");
        			return;
        		}
                try 
                {
                	if(!ifPersonExists())
                	{
                        personCtrl.createPerson(tfCCname.getText(), tfCCaddress.getText(), tfCCzipCode.getText(), tfCCcity.getText(),
                                                 tfCCphone.getText(), tfCCgsm.getText(), tfCCemail.getText(), tfCCcpr.getText());
                        personCtrl.createContact(tfCCcpr.getText());
                        updateContactTable();
                        clearTextFields();
                        JOptionPane.showMessageDialog(null,"Contact has been successfully created.");
                	}
                	else
                	{
                		 personCtrl.updatePerson(tfCCname.getText(), tfCCaddress.getText(), tfCCzipCode.getText(), tfCCcity.getText(),
                                tfCCphone.getText(), tfCCgsm.getText(), tfCCemail.getText(), tfCCcpr.getText());
                		 personCtrl.createContact(tfCCcpr.getText());
                         updateContactTable();
                         clearTextFields();
                         JOptionPane.showMessageDialog(null,"Contact has been successfully created.");
                	}
                } 
                catch (Exception r) 
                {
                        JOptionPane.showMessageDialog(null,"Error in creating Contact.");
                }
			}
		});
		btnCCadd.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnCCadd.setBounds(10, 459, 90, 31);
		contactsPanel.add(btnCCadd);
		
		JButton btnCCupdate = new JButton("Update");
		btnCCupdate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
    			if(ifContactExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Contact with this CPR does not exist.");
        			return;
        		}
    			try
    			{
    				personCtrl.updatePerson(tfCCname.getText(), tfCCaddress.getText(), tfCCzipCode.getText(), tfCCcity.getText(),
                                             tfCCphone.getText(), tfCCgsm.getText(), tfCCemail.getText(), tfCCcpr.getText());
    				updateContactTable();
    				clearTextFields();
                    JOptionPane.showMessageDialog(null,"Contact has been successfully updated.");
    			}
    			catch(Exception r)
    			{
    				JOptionPane.showMessageDialog(null,"Error in updating Contact.");
    			}
			}
		});
		btnCCupdate.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnCCupdate.setBounds(110, 459, 90, 31);
		contactsPanel.add(btnCCupdate);
		
		JButton btnCCdelete = new JButton("Delete");
		btnCCdelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifContactExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Contact with this CPR does not exist. Enter a valid CPR or double click table row.");
        			return;
        		}
                try
                {
                	if(personCtrl.deleteContact(tfCCcpr.getText()))
                     	JOptionPane.showMessageDialog(null,"Contact has been successfully deleted.");
                    else
                     	JOptionPane.showMessageDialog(null,"Cannot delete contact.");
                    updateContactTable();
                    clearTextFields();
                }
                catch(Exception r)
                {
                        JOptionPane.showMessageDialog(null,"Error in deleting Contact.");
                }
			}
		});
		btnCCdelete.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnCCdelete.setBounds(210, 459, 90, 31);
		contactsPanel.add(btnCCdelete);
		
		JLabel lblManageContacts = new JLabel("MANAGE CONTACTS");
		lblManageContacts.setHorizontalAlignment(SwingConstants.CENTER);
		lblManageContacts.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblManageContacts.setBounds(712, 7, 312, 31);
		contentPane.add(lblManageContacts);
		
		JLabel lblSearch = new JLabel("Search :");
		lblSearch.setBounds(10, 42, 110, 30);
		contentPane.add(lblSearch);
		lblSearch.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearch.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfSearch = new JTextField();
		tfSearch.setBounds(130, 45, 130, 25);
		contentPane.add(tfSearch);
		tfSearch.setColumns(10);
		tfSearch.getDocument().addDocumentListener(new DocumentListener() {  // <---
            @Override
            public void removeUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void insertUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void changedUpdate(DocumentEvent e) {}
        });
	}
	
	public void setContactFields(String cpr)
    {
    	 Contact contact = personCtrl.getContactByCpr(cpr);
    	 tfCCcpr.setText(contact.getCpr());
         tfCCname.setText(contact.getName());
         tfCCaddress.setText(contact.getAddress());
         tfCCzipCode.setText(contact.getZipCode());
         tfCCcity.setText(contact.getCity());
         tfCCphone.setText(contact.getPhone());
         tfCCgsm.setText(contact.getGsm());
         tfCCemail.setText(contact.getEmail());
    }
	
	public boolean ifEmpty()
    {
            if(tfCCcpr.getText().equals("") || tfCCname.getText().equals("") || tfCCaddress.getText().equals("") || tfCCzipCode.getText().equals("") ||
              tfCCcity.getText().equals("") || tfCCphone.getText().equals("") || tfCCgsm.getText().equals("") || tfCCemail.getText().equals(""))
            {
                    JOptionPane.showMessageDialog(null,"Some of the fields are empty.");
                    return true;
            }
            return false;
    }
	
	public boolean ifPersonExists()
    {
    	if(personCtrl.getPersonByCpr(tfCCcpr.getText()) != null)
    		return true;
    	return false;
    }
	
	public boolean ifContactExists()
    {
    	if(personCtrl.getContactByCpr(tfCCcpr.getText()) != null)
    		return true;
    	return false;
    }
	
	 public void clearTextFields()
     {
             tfCCcpr.setText("");
             tfCCname.setText("");
             tfCCaddress.setText("");
             tfCCzipCode.setText("");
             tfCCcity.setText("");
             tfCCphone.setText("");
             tfCCgsm.setText("");
             tfCCemail.setText("");
     }
	 
	 public void updateContactTable()
	 {
		 contactsT.setContact(personCtrl.listAllContacts());
		 contactsTable.setModel(contactsT);
	 }
	 
	 protected void filter()
	 {
		 sorter.setRowFilter(RowFilter.regexFilter("^(?i)"+tfSearch.getText()));
	 }
}
